//
//  CoinDetailDataService.swift
//  Crypto
//
//  Created by DaleGuo on 2023/9/26.
//

import Combine
import Foundation
import SwiftUI

class CoinDetailDataService {
    @Published var coinDetails: CoinDetailModel? = nil
    
    let coin : CoinModel
    

    var coinDetailSubscription: AnyCancellable? // 不放入set中，更加明确

    init(coin : CoinModel) {
        self.coin = coin
        getData()
    }

    func getData() {
        guard let url = URL(string: "https://api.coingecko.com/api/v3/coins/\(coin.id)?localization=false&tickers=false&market_data=false&community_data=false&developer_data=false&sparkline=false")
        else {
            return
        }

        // 如果不取消订阅，将会一直监听未来可能的数据，但我们知道不会有持续数据，所以要cancel
        // 抽离出网络访问URLSession的通用部分
        coinDetailSubscription = NetWorkingManager.download(url: url)
            // 注意json格式是globalData下包含marketData
            .decode(type: CoinDetailModel.self, decoder: JSONDecoder())
            .receive(on: DispatchQueue.main)
            .sink(receiveCompletion: NetWorkingManager.handleCompletion, receiveValue: { [weak self] returnedCoinDetails in
                self?.coinDetails = returnedCoinDetails
//                print(returnedCoinDetails)
                self?.coinDetailSubscription?.cancel() // cancle sub
            })
    }
}
